package com.wang.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class Cookie01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        PrintWriter out = resp.getWriter();

        Cookie[] cookies = req.getCookies();

        // //new一个cookie    System.currentTimeMillis()获取当前时间
        // //给cookie设置存在时间（一天）
        // cookie.setMaxAge(24 * 60 * 60);
        // //给浏览器响应一个cookie
        // resp.addCookie(cookie);

        //在从浏览器获取cookie
        //将cookie输出到浏览器
        if(cookies!=null){
            out.write("你上一次访问的时间是：");
            for(int i = 0; i < cookies.length; i++) {
              Cookie cookie = cookies[i];
              if(cookie.getName().equals("lastLoginTime")){
                  Long lastLoginTime = Long.parseLong(cookie.getValue());
                  Date date = new Date(lastLoginTime);
                  out.write(date.toLocaleString());
              }
            }
        }else{
            out.write("这是你第一次访问本站");
        }
        //获得姓名和值
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
        //给cookie设置存在时间（一天）
        cookie.setMaxAge(24 * 60 * 60);
        resp.addCookie(cookie);

        String username=req.getParameter("username");
        String pwd=req.getParameter("pwd");
        String hobbys[]=req.getParameterValues("hobbys");
        System.out.println(username+","+pwd);
        for(String hobby: hobbys){
            System.out.println(hobby);
        }
        //请求转发
        req.getRequestDispatcher("/c1").forward(req,resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
